package com.rongke.web.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rongke.commons.JsonResp;
import com.rongke.model.*;
import com.rongke.service.*;
import com.rongke.utils.RandomUtils;
import com.rongke.web.thirdapi.UdSymbol;
import com.rongke.web.thirdapi.model.PriceLineRequest;
import com.rongke.web.thirdapi.model.QuoteOptionRequest;
import com.rongke.web.yiyuan.util.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @OptionOrderController
 * @Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value="/api/optionOrder")
@Transactional
@CrossOrigin
public class OptionOrderController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private OptionOrderService optionOrderService;
    @Autowired
    private OptionsymbolService optionsymbolService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    private CapitalDetailedService capitalDetailedService;

    @RequestMapping(value = "/applyOrder",method = RequestMethod.GET)
    public JsonResp applyOrder(String underlying){
        EntityWrapper<Optionsymbol> optionsymbolEntityWrapper = new EntityWrapper<>();
        optionsymbolEntityWrapper.eq("underlying",underlying);
        List<Optionsymbol> optionsymbols = optionsymbolService.selectList(optionsymbolEntityWrapper);
        if (optionsymbols.size()>0){
            for (Optionsymbol optionsymbol:
                    optionsymbols) {
                if (optionsymbol.getTimeSpan()/60/60/24%7==0){
                    if (optionsymbol.getTimeSpan()/60/60/24/7%30==0){
                        optionsymbol.setStrTime(optionsymbol.getTimeSpan()/60/60/24/7/30+"月");
                    }
                    optionsymbol.setStrTime(optionsymbol.getTimeSpan()/60/60/24/7+"周");
                }else {
                    optionsymbol.setStrTime(optionsymbol.getTimeSpan()/60/60/24+"天");
                }
            }
            Optionsymbol optionsymbol = optionsymbols.get(0);
            UdSymbol udSymbol = new UdSymbol();
            PriceLineRequest priceLineRequest= new PriceLineRequest();
            priceLineRequest.setExch_id(optionsymbol.getExchId());
            priceLineRequest.setReq_id(RandomUtils.randomNumber(6).toString());
            priceLineRequest.setSymbol(optionsymbol.getUnderlying());
            String priceLine = udSymbol.getPriceLine(priceLineRequest);
//                System.out.println("最新价格:"+priceLine);
            Float chg = 0f;
            Float price = 0f;
            if (priceLine!=null&& !StringUtils.isEmpty(priceLine)) {
                JSONObject priceLineJson = JSONObject.parseObject(priceLine);
                JSONArray priceJson = priceLineJson.getJSONArray("priceline");
//                priceJson.getJSONArray()
//                JSONArray objects = JSONArray.parseArray(priceJson.toJSONString());
//                String[] prices = (String[])objects.get(0);
                float prePrice = Float.parseFloat(priceJson.getJSONArray(0).get(3).toString());
                price = Float.parseFloat(priceJson.getJSONArray(0).get(2).toString());
                chg = (price - prePrice) / prePrice * 100;
            }
            Map<String,Object> map = new HashMap<>();
            map.put("name",optionsymbol.getProductionName());
            map.put("underlying",underlying);
            map.put("price",price);
            map.put("chg",chg);
            map.put("optionsymbols",optionsymbols);
            return JsonResp.ok(map);
        }


        return JsonResp.fa("没有数据");
    }


    /**
     *
     * @param mdOptionId
     * @param type
     * @param nominalMoney
     * @param buyType
     * @param buyPrice
     * @return
     */
    @RequestMapping(value="/add", method = RequestMethod.GET)
    public JsonResp addOptionOrder(Long mdOptionId,int type,Float nominalMoney,Integer buyType,Float buyPrice){
        log.debug("添加");
        User loginUser = userService.findLoginUser();
        EntityWrapper<Optionsymbol> optionsymbolEntityWrapper = new EntityWrapper<>();
        optionsymbolEntityWrapper.eq("md_option_id",mdOptionId);
        Optionsymbol optionsymbol = optionsymbolService.selectOne(optionsymbolEntityWrapper);
        UdSymbol udSymbol = new UdSymbol();

        QuoteOptionRequest quoteOptionRequest = new QuoteOptionRequest();
        quoteOptionRequest.setMd_option_id(optionsymbol.getMdOptionId());
        quoteOptionRequest.setReq_id(Integer.parseInt(RandomUtils.randomString(5)));
        quoteOptionRequest.setUser_select_exp_date("0");
        List<QuoteOptionRequest> quoteOptionRequests = new ArrayList<>();
        quoteOptionRequests.add(quoteOptionRequest);
        String result = udSymbol.getQuoteOption(quoteOptionRequests);
        System.out.println(result);
        JSONArray objects = JSONArray.parseArray(result);
        JSONObject jsonObject = objects.getJSONObject(0);
//         Float.parseFloat((String) jsonObject.get("price"));
        Float realPrice =jsonObject.getFloat("price");
        Float premiumRate = jsonObject.getFloat("premium_rate");//premium_rate
        Float realMoney = nominalMoney* premiumRate;

        EntityWrapper<UserAccount> userAccountEntityWrapper = new EntityWrapper<>();
        userAccountEntityWrapper.eq("user_id",loginUser.getId());
        UserAccount userAccount = userAccountService.selectOne(userAccountEntityWrapper);
        if (userAccount.getMoney()>realMoney){
            OptionOrder optionOrder = new OptionOrder();
            System.out.println("用户id："+loginUser.getId());
            optionOrder.setUserId(loginUser.getId());
            optionOrder.setCycleTime(optionsymbol.getTimeSpan());
            optionOrder.setCreateDatetime(new Date());
            optionOrder.setExpiringDate(new Date(System.currentTimeMillis()+optionsymbol.getTimeSpan()*1000));
            optionOrder.setMdOptionId(mdOptionId);
            optionOrder.setNominalMoney(nominalMoney);
            optionOrder.setType(type);
            optionOrder.setBuyType(buyType);
            optionOrder.setRealMoney(realMoney);
            if (buyType==1){
                optionOrder.setBuyPrice(realPrice);
            }
            if (buyType==2){
                optionOrder.setBuyPrice(buyPrice);
            }

            boolean b = optionOrderService.insert(optionOrder);
            CapitalDetailed capitalDetailed = new CapitalDetailed();
            capitalDetailed.setType(2);
            capitalDetailed.setMoney(realMoney);
            capitalDetailed.setUserId(loginUser.getId());
            capitalDetailed.setCreateDatetime(new Date());
            capitalDetailed.setOrderId(optionOrder.getId());
            boolean b1 = capitalDetailedService.insert(capitalDetailed);

            userAccount.setMoney(userAccount.getMoney()-realMoney);
            boolean b2 = userAccountService.updateById(userAccount);
            if (b&&b1&&b2){
                return JsonResp.ok("申请成功");
            }
        }else {
            return JsonResp.fa("余额不足，请充值");
        }

        return JsonResp.fa("申请失败");
    }

    /**
     * @备注：用户查询订单
     * @return
     */
    @RequestMapping("selectUserOrder")
    public JsonResp selectUserOrder(){
        log.debug("用户查询订单");
        User loginUser = userService.findLoginUser();
        List<OrderTemp> orderTemps = optionOrderService.selectOrder(loginUser.getId());
        if (orderTemps.size()>0){
            return JsonResp.ok(orderTemps);
        }
        return JsonResp.fa("没有符合要求的订单");
    }
    /**
     * @修改
     * @param optionOrder
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/update", method = RequestMethod.POST)
    public JsonResp updateOptionOrder(@RequestBody OptionOrder optionOrder){
        log.debug("修改");
        optionOrderService.updateById(optionOrder);
        return JsonResp.ok(optionOrder);
    }
    /**
     * @根据id查找
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectOne", method = RequestMethod.GET)
    public JsonResp selectOptionOrder(Long id){
        log.debug("查找");
        OptionOrder optionOrder = optionOrderService.selectById(id);
        return JsonResp.ok(optionOrder);
    }


}
